using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using WeatherSystem.API.Data;
using WeatherSystem.API.Models;

namespace WeatherSystem.API.Controllers
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    // [Authorize] // 已注释，后续可重新启用
    public class UsersController : ControllerBase
    {
        private readonly WeatherDbContext _context;
        private readonly ILogger<UsersController> _logger;

        public UsersController(WeatherDbContext context, ILogger<UsersController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户列表（仅管理员）
        /// </summary>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetUsers(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string? search = null,
            [FromQuery] string? role = null,
            [FromQuery] bool? isActive = null)
        {
            try
            {
                var query = _context.Users.AsQueryable();

                // 搜索过滤
                if (!string.IsNullOrEmpty(search))
                {
                    query = query.Where(u => u.Username.Contains(search) || u.Email.Contains(search));
                }

                // 角色过滤
                if (!string.IsNullOrEmpty(role))
                {
                    if (Enum.TryParse<UserRole>(role, true, out var userRole))
                    {
                        query = query.Where(u => u.Role == userRole);
                    }
                }

                // 状态过滤
                if (isActive.HasValue)
                {
                    query = query.Where(u => u.IsActive == isActive.Value);
                }

                // 总数
                var totalCount = await query.CountAsync();

                // 分页优化 - 使用投影减少数据传输
                var users = await query
                    .OrderBy(u => u.Username)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .AsNoTracking()
                    .Select(u => new
                    {
                        id = u.Id,
                        username = u.Username,
                        email = u.Email,
                        role = u.Role.ToString(),
                        isActive = u.IsActive,
                        createdAt = u.CreatedAt,
                        updatedAt = u.UpdatedAt,
                        failedLoginAttempts = u.FailedLoginAttempts,
                        lockoutEndTime = u.LockoutEndTime
                    })
                    .ToListAsync();

                return Ok(new
                {
                    users = users,
                    pagination = new
                    {
                        page = page,
                        pageSize = pageSize,
                        totalCount = totalCount,
                        totalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户列表失败");
                return StatusCode(500, new { message = "获取用户列表失败" });
            }
        }

        /// <summary>
        /// 获取指定用户信息（仅管理员）
        /// </summary>
        [HttpGet("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetUser(Guid id)
        {
            try
            {
                var user = await _context.Users
                    .FirstOrDefaultAsync(u => u.Id == id);

                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                return Ok(new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    role = user.Role,
                    isActive = user.IsActive,
                    createdAt = user.CreatedAt,
                    updatedAt = user.UpdatedAt
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户信息失败，用户ID: {id}");
                return StatusCode(500, new { message = "获取用户信息失败" });
            }
        }

        /// <summary>
        /// 更新用户角色（仅管理员）
        /// </summary>
        [HttpPut("{id}/role")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateUserRole(Guid id, [FromBody] UpdateUserRoleRequest request)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                if (currentUserId == id)
                {
                    return BadRequest(new { message = "不能修改自己的角色" });
                }

                var user = await _context.Users
                    .FirstOrDefaultAsync(u => u.Id == id);

                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                // 验证角色
                if (!Enum.TryParse<UserRole>(request.Role, true, out var newRole))
                {
                    return BadRequest(new { message = "无效的角色" });
                }

                user.Role = newRole;
                user.UpdatedAt = DateTime.UtcNow;

                await _context.SaveChangesAsync();

                _logger.LogInformation($"管理员更新用户 {user.Username} 的角色为 {request.Role}");

                return Ok(new { message = "角色更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户角色失败，用户ID: {id}");
                return StatusCode(500, new { message = "更新角色失败" });
            }
        }

        /// <summary>
        /// 启用/禁用用户（仅管理员）
        /// </summary>
        [HttpPut("{id}/status")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateUserStatus(Guid id, [FromBody] UpdateUserStatusRequest request)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                if (currentUserId == id)
                {
                    return BadRequest(new { message = "不能修改自己的状态" });
                }

                var user = await _context.Users
                    .FirstOrDefaultAsync(u => u.Id == id);

                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                user.IsActive = request.IsActive;
                user.UpdatedAt = DateTime.UtcNow;

                await _context.SaveChangesAsync();

                var action = request.IsActive ? "启用" : "禁用";
                _logger.LogInformation($"管理员{action}用户 {user.Username}");

                return Ok(new { message = $"用户{action}成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户状态失败，用户ID: {id}");
                return StatusCode(500, new { message = "更新状态失败" });
            }
        }

        /// <summary>
        /// 删除用户（仅管理员）
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteUser(Guid id)
        {
            try
            {
                var currentUserId = GetCurrentUserId();
                if (currentUserId == id)
                {
                    return BadRequest(new { message = "不能删除自己的账户" });
                }

                var user = await _context.Users
                    .FirstOrDefaultAsync(u => u.Id == id);

                if (user == null)
                {
                    return NotFound(new { message = "用户不存在" });
                }

                // 检查用户是否有关联数据
                // 注意：当前数据模型中WeatherData和DataCollectionLog没有直接的用户关联字段
                // 这里暂时跳过关联数据检查，直接删除用户
                var hasWeatherData = false;
                var hasLogs = false;

                if (hasWeatherData || hasLogs)
                {
                    // 如果有关联数据，只是禁用用户而不删除
                    user.IsActive = false;
                    user.UpdatedAt = DateTime.UtcNow;
                    await _context.SaveChangesAsync();

                    _logger.LogInformation($"管理员禁用用户 {user.Username}（因为有关联数据）");
                    return Ok(new { message = "用户已禁用（因为存在关联数据）" });
                }
                else
                {
                    // 没有关联数据，可以直接删除
                    _context.Users.Remove(user);
                    await _context.SaveChangesAsync();

                    _logger.LogInformation($"管理员删除用户 {user.Username}");
                    return Ok(new { message = "用户删除成功" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除用户失败，用户ID: {id}");
                return StatusCode(500, new { message = "删除用户失败" });
            }
        }

        /// <summary>
        /// 获取用户统计信息（仅管理员）
        /// </summary>
        [HttpGet("statistics")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetUserStatistics()
        {
            try
            {
                var totalUsers = await _context.Users.CountAsync();
                var activeUsers = await _context.Users.CountAsync(u => u.IsActive);
                var adminUsers = await _context.Users.CountAsync(u => u.Role == UserRole.Admin);
                var regularUsers = await _context.Users.CountAsync(u => u.Role == UserRole.User);

                // 最近30天注册的用户
                var thirtyDaysAgo = DateTime.UtcNow.AddDays(-30);
                var recentRegistrations = await _context.Users
                    .CountAsync(u => u.CreatedAt >= thirtyDaysAgo);

                return Ok(new
                {
                    totalUsers = totalUsers,
                    activeUsers = activeUsers,
                    inactiveUsers = totalUsers - activeUsers,
                    adminUsers = adminUsers,
                    regularUsers = regularUsers,
                    recentRegistrations = recentRegistrations
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户统计信息失败");
                return StatusCode(500, new { message = "获取统计信息失败" });
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        private Guid? GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return Guid.TryParse(userIdClaim, out var userId) ? userId : null;
        }

        #endregion
    }

    #region 请求模型

    /// <summary>
    /// 更新用户角色请求模型
    /// </summary>
    public class UpdateUserRoleRequest
    {
        [Required(ErrorMessage = "角色不能为空")]
        public string Role { get; set; } = string.Empty;
    }

    /// <summary>
    /// 更新用户状态请求模型
    /// </summary>
    public class UpdateUserStatusRequest
    {
        [Required]
        public bool IsActive { get; set; }
    }

    #endregion
}